package com.szholly.pro.watergas_server.ps.schedule;




import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.RowBase;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.service.DataReportService;
import com.szholly.pro.watergas_server.ps.service.WaterQualityAnalysisService;
import com.szholly.utils.spring.SpringBeanFactory;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import lrq.common.MyLog;
/**
 *  定时任务，每天定时生成日、 周、月、季、年的水质类别数据
 * @author 熊伟
 *
 */
public class CreateWaterTypeData  implements Job {
	static Logger log;
	
	@Autowired
	DataReportService dataReportService;
	
	@Autowired
	WaterQualityAnalysisService waterQualityAnalysisService;
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		if(log == null){
			log = MyLog.getLogger("CreateWaterTypeData");
		}
		 
		try {
		   Calendar cal=Calendar.getInstance();
		   Calendar realCal = Calendar.getInstance();
		   
		   //生成水质类别日数据
		   realCal.setTime(cal.getTime());  
		   CreateDayWaterType(realCal);
		   //生成水质类别周数据
		   realCal.setTime(cal.getTime());  
		   CreateWeekWaterType(realCal);
	       //生成水质类别月数据
	       realCal.setTime(cal.getTime());  
	       CreateMonthWaterType(realCal);  
	       //生成水质类别季数据
	       realCal.setTime(cal.getTime());  
	       CreateQuarterWaterType(realCal);
	       //生成水质类别年数据
	       realCal.setTime(cal.getTime());  
	       CreateYearWaterType(realCal);
		   
		} catch (Exception e) {
			log.error("生成水质类别数据出错",e);
		}
	}
	
	/**
	 * 
	 * 根据monitor_data_day中的均值数据，生成并插入相应的水质类别数据（day_water_type）
	 * xwei
	 * 2017年05月17日
	 * @return
	 * @throws ParseException 
	 */
	public void CreateDayWaterType(Calendar cal) throws ParseException {
//        //获取开始时间与结束时间
		try {
			Date endTime = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, -1);
			Date startTime = cal.getTime();	      
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String strStartTime = sdf.format(startTime);
			String strEndTime = sdf.format(endTime);
			String tableName = "monitor_data_day";
			String waterTypeTableName = "day_water_type";
			CreateTypeData(sdf.parse(strStartTime),sdf.parse(strEndTime),tableName,waterTypeTableName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * 根据monitor_data_week中的均值数据，生成并插入相应的水质类别数据（week_water_type）
	 * xwei
	 * 2017年05月17日
	 * @return
	 * @throws ParseException 
	 */
	private void CreateWeekWaterType(Calendar cal){
		log.info("开始生成周数据");
		try{
			//判断当前时间是否为周一
	        if(cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY)
	        {
	        	return;
	        }
	        
	        //获取开始时间与结束时间
			Date endTime = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, -7);
			Date startTime = cal.getTime();
			String tableName = "monitor_data_week";
			String waterTypeTableName = "day_water_week";
			//设置周一为一周的开头,week=1时，应设置为53周
			cal.setFirstDayOfWeek(Calendar.MONDAY);
			int week = cal.get(Calendar.WEEK_OF_YEAR);
			if(week == 1)
			{
				week = 53;
			}
			CreateTypeData(startTime,endTime,tableName,waterTypeTableName);
		} catch(Exception e)
		{
			log.error("生成周数据出错",e);
		}
	}
	
	
	/**
	 * 
	 * 根据monitor_data_month中的均值数据，生成并插入相应的水质类别数据（month_water_type）
	 * xwei
	 * 2017年05月17日
	 * @return
	 * @throws ParseException 
	 */
	private void CreateMonthWaterType(Calendar cal){
		log.info("开始生成月数据");
		try{
			//判断当前时间是否为1号
	        if(cal.get(Calendar.DAY_OF_MONTH) != 1)
	        {
	        	return;
	        }
	        
	        //获取开始时间与结束时间
			Date endTime = cal.getTime();
			cal.add(Calendar.MONTH, -1);
			Date startTime = cal.getTime();
			String tableName = "monitor_data_week";
			String waterTypeTableName = "week_water_type";
			CreateTypeData(startTime,endTime,tableName,waterTypeTableName);
		} catch(Exception e)
		{
			log.error("生成月数据出错",e);
		}
	}
	
	/**
	 * 
	 * 根据monitor_data_quarter中的均值数据，生成并插入相应的水质类别数据（quarter_water_type）
	 * xwei
	 * 2017年05月17日
	 * @return
	 * @throws ParseException 
	 */
	private void CreateQuarterWaterType(Calendar cal){
		log.info("开始生成季数据");
		try{
			//判断当前时间是否为1号,是否为季度的第一个月
	        if(cal.get(Calendar.DAY_OF_MONTH) != 1 || (cal.get(Calendar.MONTH)%3)!=0)
	        {
	        	return;
	        }
	             
	        //获取开始时间与结束时间
			Date endTime = cal.getTime();
			cal.add(Calendar.MONTH, -3);
			Date startTime = cal.getTime();
	       
			String tableName = "monitor_data_quarter";
			String waterTypeTableName = "quarter_water_type";
			CreateTypeData(startTime,endTime,tableName,waterTypeTableName);
		} catch(Exception e)
		{
			log.error("生成季数据出错",e);
		}
	}
	
	
	/**
	 * 
	 * 根据monitor_data_year中的均值数据，生成并插入相应的水质类别数据（year_water_type）
	 * xwei
	 * 2017年05月17日
	 * @return
	 * @throws ParseException 
	 */
	private void CreateYearWaterType(Calendar cal){
		log.info("开始生成年数据");
		try{
			//判断当前时间当年第一天
	        if(cal.get(Calendar.DAY_OF_YEAR) != 1)
	        {
	        	return;
	        }
	           
	        //获取开始时间与结束时间
			Date endTime = cal.getTime();
			cal.add(Calendar.YEAR, -1);
			Date startTime = cal.getTime();
	       
			String tableName = "monitor_data_year";
			String waterTypeTableName = "year_water_type";
			CreateTypeData(startTime,endTime,tableName,waterTypeTableName);
		} catch(Exception e)
		{
			log.error("生成年数据出错",e);
		}
	}
	
	
	/**
	 * 生成数据
	 * xwei
	 * 2017年05月17日
	 */
	private void CreateTypeData(Date startTime,Date endTime,String tableName,String waterTypeTableName)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1、查询地表水所有站点 （MN号）
        String sql = "select t1.id,t1.device_num from BC_COLLECTION_INFO t1 "
        		+ " left join BC_SITE_INFO t2 on t1.SITE_ID=t2.exp_no"
        		+ " where t2.STATION_CATEGORY in('1') order by t2.station_category";
		List<RowBase> rows = DataUtil.getSelectRows(sql, null);
		//2、循环站点，查询每个站点的污染物数据均值
		for(int i=0;i<rows.size(); i++) {
			String Mn = rows.get(i).getSafeString("device_num");
			String parmSql = "select mn,parmname,avg,datatime,date_text from "+tableName+" t1,\n"
					+" monitor_station t2,BC_COLLECTION_INFO t3 "
					+" where t2.code= t3.site_id\n"
					+"and t3.device_num= t1.mn\n"
					+"and t2.STATION_CATEGORY='1' \n"
					+" and t1.mn ="+"'"+Mn+"'"
					
					+ "and datatime >= @startDate\n"
					+" and datatime <= @endDate\n"
					+" and parmname not in ('COMP_POLL_INDEX','water_speed','water_depth','sd','B01','B01TOTAL','phtem','wind_speed')\n"
					+"group by mn,parmname,avg,datatime,date_text order by datatime desc";
			
			List<GlobalParameter> pc = new ArrayList<>();
			ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
			ITable pTable = tableFactory.openTable("POLLDATA");
			pc.add(new GlobalParameter("startDate", startTime));
			pc.add(new GlobalParameter("endDate", endTime));
			List<RowBase> queryParmValueList = DataUtil.getSelectRows(parmSql, pc,pTable);
			
			//3、查询所有参数的水质类别标准值
			Map<String,String> params = new HashMap<String, String>();
			params.put("category","SURFACE_WATER");
			List<RowBase> standardRows = getWaterQualityStandards(params);
			//4、根据水质类别标准判别污染物的水质类别
			for(int k = 0;k < queryParmValueList.size();k++) {
				RowBase row = new RowBase();
				row = queryParmValueList.get(k);
				double value = row.getSafeDouble("avg");
				String MN = row.getSafeString("mn");
				String parmname = row.getSafeString("parmname");
				String dateText = row.getSafeString("date_text");
				String dataTime = row.getSafeString("datatime");
				//根据标准计算器水质类别
				String waterType = getWaterType(parmname,value,standardRows);
				double Value=0;
				if("I".equals(waterType)) {
					Value=1;
				} else if("II".equals(waterType)) {
					Value=2;
				}else if("III".equals(waterType)) {
					Value=3;
				}else if("IV".equals(waterType)) {
					Value=4;
				}else if("V".equals(waterType)) {
					Value=5;
				} else {
					Value=6;
				}
				//5、将生成的水质类别数据入库。

				String insertSql = "insert into " +waterTypeTableName+"(DATA_TEXT,PARMNAME,MN,WATER_TYPE,GUID,DATATIME,VALUE) "
						+ "values (@data_text, @parmname, @mn,@waterType, sys_guid(), @datatime, @value)";
				
				List<GlobalParameter> parms = new ArrayList<>();
				parms.add(new GlobalParameter("parmname", parmname));
				parms.add(new GlobalParameter("mn", MN));
				parms.add(new GlobalParameter("value", Value));
				parms.add(new GlobalParameter("datatime", sdf.parse(dataTime)));
				parms.add(new GlobalParameter("data_text", dateText));
				parms.add(new GlobalParameter("waterType", waterType));
				DataUtil.ExecuteUpdateSql(insertSql, parms);	
			}				
		}
	}
	/**
	 * 通过水质类别标准，计算出对应的水质类别
	 * @param parmname
	 * @param value
	 * @param standardRows
	 * @return
	 */
	public String getWaterType(String parmname,double value,List<RowBase> standardRows){
		int maxQualityClass=0;
		int qualityClass=0;
		for(RowBase r:standardRows){
			if(r.getSafeString("ITEM").equals(parmname)) {
				if(value>=r.getSafeDouble("MINIMUM") && value<=r.getSafeDouble("MAXIMUM")){
					qualityClass = r.getSafeInt("QUALITY_CLASS");
				}
			}
			if(qualityClass > maxQualityClass){
				maxQualityClass = qualityClass;
			}
		}
		String result="";
		if(maxQualityClass==1) {
			result="I";
		} else if(maxQualityClass==2) {
			result="II";
		} else if(maxQualityClass==3) {
			result="III";
		} else if(maxQualityClass==4) {
			result="IV";
		} else if(maxQualityClass==5) {
			result="V";
		} else{
			result="劣V";
		}
		return result;
	}
	/**
	 * 获取水质标准
	 * @param params
	 * @return
	 */
	public List<RowBase> getWaterQualityStandards(Map<String,String> params){
		String sql = "select * from BC_QUALITY_STANDARD t where 1=1 and t.category='SURFACE_WATER' \n";
		
		List<GlobalParameter> listParams = new ArrayList<>();
		if(params.containsKey("category")){
			sql += " and t.category=@category";
			listParams.add(new GlobalParameter("category",params.get("category")));
		}
		if(params.containsKey("item")){
			sql += " and t.item=@item";
			listParams.add(new GlobalParameter("item",params.get("item")));
		}
		return DataUtil.getSelectRows(sql, listParams);
	}
}
